<?php

namespace Miniapp\Controllers;

define('WX_GJGJ_SERVICE_NUMBER_APPID', 'wx3ba1d4c501eee62b');
define('WX_GJGJ_SERVICE_NUMBER_APPSECRET', 'dc2a61136bde16b55def8b4fedc052b9');

class ScenarioController extends BaseController {

    protected $openid;
    protected $token;
    protected $wxNickname;
    protected $wxImg;
    protected $city;
    protected $sex; //用户的性别，值为1时是男性，值为2时是女性，值为0时是未知
    protected $appid = WX_GJGJ_SERVICE_NUMBER_APPID;
    protected $secret = WX_GJGJ_SERVICE_NUMBER_APPSECRET;
    protected $callback = "http%3A%2F%2Fapp.gjgj.com%2FWxauth%2FWechatWebAuthentication"; //urlencode("http://app.gjgj.com/Wxauth/WechatWebAuthentication");GJGJ服务号通用鉴权页面
    protected $redirectUrl;

    public function initialize() {
        parent::initialize();
        header('Access-Control-Allow-Origin:*');
        //获取当前请求页面
        $url = 'http://' . $_SERVER['SERVER_NAME'] . ':' . $_SERVER["SERVER_PORT"] . $_SERVER["REQUEST_URI"];
        //设置真实跳转页面
        $trueCallback = base64_encode($url);
        $this->callback = $this->callback . (urldecode("?trueCallback=") . $trueCallback);
        //定义获取TOKEN出错时重新跳转到首页URL的请求
        $callbackIndexUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" . $this->appid . "&redirect_uri=" . $this->callback . "&response_type=code&scope=snsapi_userinfo&state=0#wechat_redirect";
        $this->redirectUrl = $callbackIndexUrl;
        $openid = $_COOKIE["openid"];
        if (empty($openid)) {
            if (empty($_GET['code'])) {
                //获取当前页面跳转URL
                header('Location: ' . $this->redirectUrl);
                exit();
            }
            $tokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" . $this->appid . "&secret=" . $this->secret . "&code=" . $_GET['code'] . "&grant_type=authorization_code";
            $tokenStc = file_get_contents($tokenUrl);
            $tokenResult = json_decode($tokenStc, true);
            if (isset($tokenResult['access_token'])) {
                setcookie("token", $tokenResult['access_token'], time() + 3600 * 24 * 30, "/", "gjgj.com");
                setcookie("openid", $tokenResult['openid'], time() + 3600 * 24 * 30, "/", "gjgj.com");
                $this->openid = $tokenResult['openid'];
                $this->token = $tokenResult['access_token'];
                $userInfoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" . $this->token . "&openid=" . $this->openid . "&lang=zh_CN";
                $userInfoStc = file_get_contents($userInfoUrl);
                $userInfoResult = json_decode($userInfoStc, true);
                $this->wxImg = $userInfoResult['headimgurl'];
                $this->wxNickname = $userInfoResult['nickname'];
                $this->sex = $userInfoResult['sex'];
                $this->city = $userInfoResult['city'];
                setcookie("wxImg", $userInfoResult['headimgurl'], time() + 3600 * 24 * 30, "/", "gjgj.com");
                setcookie("wxNickname", $userInfoResult['nickname'], time() + 3600 * 24 * 30, "/", "gjgj.com");
                setcookie("sex", $userInfoResult['sex'], time() + 3600 * 24 * 30, "/", "gjgj.com");
                setcookie("city", $userInfoResult['city'], time() + 3600 * 24 * 30, "/", "gjgj.com");
            } else {
                header('Location: ' . $this->redirectUrl);
                exit();
            }
        } else {
            $this->openid = $openid;
            $this->token = $_COOKIE["token"];
            $this->wxImg = $_COOKIE["wxImg"];
            $this->wxNickname = $_COOKIE["wxNickname"];
            $this->sex = $_COOKIE["sex"];
            $this->city = $_COOKIE["city"];
        }
    }

    public function indexAction() {
        $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
        $shareUrl = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
        $jssdk = Lib('WxJssdk', ['appId' => $this->appid, 'appSecret' => $this->secret]);
        $signPackage = $jssdk->GetSignPackage($shareUrl);
        $this->view->shareTitle = $this->wxNickname . "邀请你来是大腿实习";
        $this->view->sharePyTitle = "是大腿实习试用期，你来挑战吗？";
        $this->view->signPackage = $signPackage;
        $this->view->shareDesc = $this->wxNickname . "邀请你来是大腿实习";
        $this->view->shareUrl = $signPackage['shareUrl'];
        $this->view->startId = $_REQUEST['startId'] ? $_REQUEST['startId'] : 0;
        $this->view->pick("Scenario/index");
    }

    public function getScenarioAction() {
        $id = 1;
        $result = service('Scenario/ScenarioService')->getScenario($id, $this->wxImg, $this->wxNickname);
        $this->renderJson($result);
    }

    /**
     * 用户打赏
     */
    public function createOrderAction() {
        header('Content-Type:application/json; charset=utf-8');
        $cash = $_REQUEST['cash'];
        $type = $_REQUEST['type'];
        $payService = service("Pay/RewardPayService");
        //创建订单
        $result = $payService->createPayOrder($cash, $type);
        //调用统一下单
        $resulst2 = lib("WxPayServiceNumber")->unifiedorder($this->openid, $result['orderNo'], round($cash, 2) * 100, $notify_url = "http://rpg.gjgj.com/Pay/wxRewardPayOrderCallBack", $body = "打赏");
        //生成小程序需要的paySign
        $resulst3 = lib("WxPayServiceNumber")->createPaySign($resulst2);
        $result = array_merge($result, $resulst3);
        $this->renderJson($result);
    }

}
